package com.qf.mybatis03.entity;

import cn.hutool.core.util.RandomUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Book implements Serializable {
    private Integer id;
    private String name;
    private String author;
    private String publish;
    private Integer sort;

    //产生一本新的随机性的book
    public static Book randomBook() {
        Book book = new Book();
        //产生随机书名（字符串）
        String name = RandomUtil.randomString(20);
        //产生随机作者
        String author = RandomUtil.randomString(10);
        //随机出版社
        String publish = RandomUtil.randomString(25);
        //随机排名
        int sort = RandomUtil.randomInt(0, 1000000);
        book.setName(name);
        book.setAuthor(author);
        book.setPublish(publish);
        book.setSort(sort);
        return book;
    }

    public static List<Book> randomBook(Integer size) {
        ArrayList<Book> books = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            books.add(randomBook());
        }
        return books;
    }

    //把book对象转换成csv字符串
    public String toCSVString() {
        return this.name + "," + this.author + "," + this.publish + "," + this.sort;
    }

    //把，分割的字符串转换成book对象
    public static Book csvToBook(String csv) {
        String[] split = csv.split(",");
        Book book = new Book();
        book.setName(split[0]);
        book.setAuthor(split[1]);
        book.setPublish(split[2]);
        book.setSort(Integer.valueOf(split[3]));
        return book;
    }

    @Override
    public String toString() {
        return this.name + "," + this.author + "," + this.publish + "," + this.sort;
    }
}











